package com.omf.free;

import android.app.Activity;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

import java.util.*;


public class Animals_free extends Activity{
	// Declare string array that holds names of all animals
	ArrayList<String> names = new ArrayList<String>();
	
	// Declare integer array that holds color values of all animals
	int colors[] = new int[15];
	
	// Declare variable to hold id of current animal
	int id;
	
	// Declare variable to keep track of position in randomized array of ids
	int position;
	
    // Create integer array to hold id's of animals
    int animals[] = new int[15];
    
    // Declare integer to store state of audio being played
    int audio = 0;
    
    // Declare RelativeLayout to display animal picture as background
    RelativeLayout background;
    
    // Declare TextView to later display name of animal
    TextView name;
    
    // Declare GestureDetector
    GestureDetector swipe_detector;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.animals);
        
        // Check if saved state is not empty 
        if(savedInstanceState != null){
        	// If so save the previous animals array it into animals and previous position
        		// into position
        	animals = savedInstanceState.getIntArray("ids");
        	position = savedInstanceState.getInt("pos");
        }
        
        // Else make new animals array and start position at 0
        else{
        	// Instantiate random number generator
        	Random randomGenerator = new Random();
	
			// Repeat selection method 15 times to pick all 15 animals
			for(int i = 0; i < 15; i++){
				// Generate a random number between 0 and 14
				int choice = randomGenerator.nextInt(15);
			
				// Make sure choice isn't already in animals
				for(int j = 0; j < i; j++){
					if(choice == animals[j]){
						// If it is a repeat then set choice to -1 and break for loop
						choice = -1;
						break;
					}
				}
		
				// Check if choice is -1
				if(choice == -1){
					// If so random id chosen was a repeat so decrement i and repeat this
						// iteration of selection method
					i--;
				}
		
				// Else assign id value in choice to current position in animals
				else{
					animals[i] = choice;
				}
			}
			
			// Initialize position to 0
			position = 0;
        }
        
        // Populate names array with names of animals
        names.add("Cow");
        names.add("Pig");
        names.add("Dog");
        names.add("Horse");
        names.add("Sheep");
        names.add("Cat");
        names.add("Chicken");
        names.add("Squirrel");
        names.add("Duck");
        names.add("Frog");
        names.add("Turkey");
        names.add("Lion");
        names.add("Tiger");
        names.add("Bear");
        names.add("Monkey");
        
        // Populate colors array with color values for each animal
        colors[0] = 0xff000000;
        colors[1] = 0xffffffff;
        colors[2] = 0xffffffff;
        colors[3] = 0xff000000;
        colors[4] = 0xffffffff;
        colors[5] = 0xffffffff;
        colors[6] = 0xffffffff;
        colors[7] = 0xff000000;
        colors[8] = 0xff000000;
        colors[9] = 0xffffffff;
        colors[10] = 0xffffffff;
        colors[11] = 0xffffffff;
        colors[12] = 0xffffffff;
        colors[13] = 0xffffffff;
        colors[14] = 0xff000000;
        
		// Get current id
		id = animals[position];
		
		// Instantiate TextView
		name = (TextView) findViewById(R.id.title2);
		
		// Set color of name to be color for this animal
		name.setTextColor(colors[id]);
		
		// Put animals name in name
		name.setText(names.get(id));
		
		// Instantiate picture id to 0
		int picture_id = 0;
		
		// Check if current orientation is portrait
		if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
			// If so convert id of animal to id of its portrait picture
			picture_id = id2Picture1(id);
		}
		
		// Else current orientation is landscape
		else{
			// If so convert id of animal to id of its landscape picture
			picture_id = id2Picture2(id);
		}
		
		// Instantiate RelativeLayout
		background = (RelativeLayout) findViewById(R.id.relativeLayout1);
		
		// Load animals picture into background of layout
		background.setBackgroundResource(picture_id);
		
        // Instantiate new gestureListener
        swipe_detector = new GestureDetector(new gestureListener());
        
        // Create onTouchListener for picture
        background.setOnTouchListener(new View.OnTouchListener() {
			// Override onTouch function
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// Check if a swipe left or right was performed using gestureListener
				if(swipe_detector.onTouchEvent(event)){
					// If so return true
					return true;
				}
				
				// else return false
				else{
					return false;
				}
			}
		});

        // Instantiate left and right buttons
        Button left = (Button) findViewById(R.id.left);
        Button right = (Button) findViewById(R.id.right);
        
        // Set onClickListener for for left
        left.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Check if audio is 0
				if(audio == 0){
					// If so change id to id of next animal and increase position (wrapping 
						// around the end if at last animal)
					position = (position - 1);
					if(position < 0){
						position = 14;
					}
					id = animals[position];

					// Set color of name to be color for this animal
					name.setTextColor(colors[id]);

					// Put animals name in name
					name.setText(names.get(id));

					// Instantiate picture id to 0
					int picture_id = 0;

					// Check if current orientation is portrait
					if(Animals_free.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
						// If so convert id of animal to id of its portrait picture
						picture_id = id2Picture1(id);
					}

					// Else current orientation is landscape
					else{
						// If so convert id of animal to id of its landscape picture
						picture_id = id2Picture2(id);
					}

					// Instantiate RelativeLayout
					background = (RelativeLayout) findViewById(R.id.relativeLayout1);

					// Load animals picture into background of layout
					background.setBackgroundResource(picture_id);
				}
			}
		});
        
        // Set onClickListener for right
        right.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Check if audio is 0
				if(audio == 0){
					// If so change id to id of next animal and increase position (wrapping 
						// around the end if at last animal)
					position = (position + 1)%15;
					id = animals[position];

					// Set color of name to be color for this animal
					name.setTextColor(colors[id]);

					// Put animals name in name
					name.setText(names.get(id));

					// Instantiate picture id to 0
					int picture_id = 0;

					// Check if current orientation is portrait
					if(Animals_free.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
						// If so convert id of animal to id of its portrait picture
						picture_id = id2Picture1(id);
					}

					// Else current orientation is landscape
					else{
						// If so convert id of animal to id of its landscape picture
						picture_id = id2Picture2(id);
					}

					// Instantiate RelativeLayout
					background = (RelativeLayout) findViewById(R.id.relativeLayout1);

					// Load animals picture into background of layout
					background.setBackgroundResource(picture_id);
				}
			}
		});

        // Instantiate sound button
        Button sound = (Button) findViewById(R.id.sound);
        
        // Start onClickListener for sound
        sound.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Check if audio is 0
				if(audio == 0){
					// Convert current animals id to the id of its name
					int name_id = id2Name(id);

					// Instantiate new media player
					MediaPlayer mp1 = MediaPlayer.create(getApplicationContext(), name_id);
					
					// Make sure mp1 is non-null
					if(mp1 != null){
						// Play correct message
						mp1.start();

						// Set audio to 1
						audio = 1;

						// Set listener to wait for on completion of mp1
						mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
							// Override on completion
							@Override
							public void onCompletion(MediaPlayer mp){
								// Release mp1
								mp.release();

								// Convert id of current animal to id of its sound file
								int sound_id = id2Sound(id);

								// Instantiate new media player
								MediaPlayer mp2 = MediaPlayer.create(getApplicationContext(), sound_id);

								// Make sure mp2 is non-null
								if(mp2 != null){
									// Play correct message
									mp2.start();

									// Set listener to wait for on completion of mp1
									mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
										// Override on completion
										@Override
										public void onCompletion(MediaPlayer mp){
											// Release mp1
											mp.release();

											// Set audio back to 0
											audio = 0;
										}
									});
								}
								
								// Else media player could not be instantiated
								else{
									// Give user error message
									Toast.makeText(getApplicationContext(), "Error: Could not play animal's sound", Toast.LENGTH_SHORT).show();
								}
							}
						});
					}
					
					// Else media player could not be instantiated
					else{
						// Give user error message
						Toast.makeText(getApplicationContext(), "Error: Could not play animal's name", Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
    }
    
    // Extend SimpleOnGestureListener to implement left and right swiping actions
    class gestureListener extends GestureDetector.SimpleOnGestureListener{
    	// Override onFling function
    	@Override
    	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
    		// Get view configuration
    		ViewConfiguration vc = ViewConfiguration.get(getApplicationContext());
    		
    		// Set swipeMaxOffPath to be scaled touch slop value for screen
    		//int flingMaxOffPath = vc.getScaledTouchSlop();
    		
    		// Set swipeMinDistance to be scaled touch slop value for screen
    		int flingMinDistance = vc.getScaledTouchSlop();
    		
    		// Set swipeMinVelocity to be minimum fling velocity scaled for screen
    		int flingMinVelocity = vc.getScaledMinimumFlingVelocity();
    		
    		// Check if audio is 0
    		if(audio == 0){
    			// If so continue detecting and processing fling motion
    			try {
    				// Otherwise continue and check if motion was right to left
    				if(e1.getX() - e2.getX() > flingMinDistance && Math.abs(velocityX) > flingMinVelocity) {
    					// If so change id to id of next animal and increase position (wrapping 
                			// around the end if at last animal)
    					position = (position + 1)%15;
    					id = animals[position];

    					// Set color of name to be color for this animal
    					name.setTextColor(colors[id]);
            		
    					// Put animals name in name
    					name.setText(names.get(id));

    					// Instantiate picture id to 0
    					int picture_id = 0;
            		
    					// Check if current orientation is portrait
    					if(Animals_free.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
    						// If so convert id of animal to id of its portrait picture
    						picture_id = id2Picture1(id);
    					}
            		
    					// Else current orientation is landscape
    					else{
    						// If so convert id of animal to id of its landscape picture
    						picture_id = id2Picture2(id);
    					}

    					// Instantiate RelativeLayout
    					background = (RelativeLayout) findViewById(R.id.relativeLayout1);
            		
    					// Load animals picture into background of layout
    					background.setBackgroundResource(picture_id);
            		
    					// Return true
    					return true;
    				}  
                
    				// Else check if motion was from left to right
    				else if (e2.getX() - e1.getX() > flingMinDistance && Math.abs(velocityX) > flingMinVelocity) {
    					// If so change id to id of next animal and increase position (wrapping 
            				// around the end if at last animal)
    					position = (position - 1);
    					if(position < 0){
    						position = 14;
    					}
    					id = animals[position];

    					// Set color of name to be color for this animal
    					name.setTextColor(colors[id]);
            		
    					// Put animals name in name
    					name.setText(names.get(id));
            		
    					// Instantiate picture id to 0
    					int picture_id = 0;
            		
    					// Check if current orientation is portrait
    					if(Animals_free.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
    						// If so convert id of animal to id of its portrait picture
    						picture_id = id2Picture1(id);
    					}
            		
    					// Else current orientation is landscape
    					else{
    						// If so convert id of animal to id of its landscape picture
    						picture_id = id2Picture2(id);
    					}

    					// Instantiate RelativeLayout
    					background = (RelativeLayout) findViewById(R.id.relativeLayout1);
            		
    					// Load animals picture into background of layout
    					background.setBackgroundResource(picture_id);
            		
    					// Return true
    					return true;
    				}
    			} 
    		
    			// Catch any exceptions thrown
    			catch (Exception e) {
    				// Do nothing
    			}
    		}
    		
    		// If none of these apply return false
            return false;
    	}
    	
    	// Override onDown function
    	@Override
    	public boolean onDown(MotionEvent event){
    		return true;
    	}
    }
    
    // Override onSavedInstanceState function
    @Override
    public void onSaveInstanceState(Bundle outState){
    	// Call super function
    	super.onSaveInstanceState(outState);
    	
    	// Put animals array into outState bundle
    	outState.putIntArray("ids", animals);
    	
    	// Put position into outState bundle
    	outState.putInt("pos", position);
    }
    
    // Make function to convert an animals id to the id of its portrait picture
    int id2Picture1(int id){
    	return id + 0x7f020000;
    }
    
    // Make function to convert an animals id to the id of its landscape picture
    int id2Picture2(int id){
    	return id + 0x7f02000f;
    }
    
    // Make function to convert an animals id to the id of its sound
    int id2Sound(int id){
    	return id + 0x7f040000;
    }
    
    // Make function to convert an animals id to the id of its name
    int id2Name(int id){
    	return id + 0x7f040000 + 15;
    }
}

